package service;

import dao.UserDao;
import domain.User;
import exception.ActiveUserException;
import exception.LoginException;
import utils.MailUtils;
import utils.ResponseCode;

import java.util.Date;
import java.sql.SQLException;

public class UserService {
    private UserDao userDao=new UserDao();
    //    面向业务
    public  void active(String activeCode) throws ActiveUserException{
        try {
            User user=userDao.findUserByActiveCode(activeCode);
            if (user==null){
                throw new ActiveUserException(ResponseCode.ERROR_ACTIVE);
            }
            Date registTime=user.getRegistTime();
            long currentTime=System.currentTimeMillis();
            long time=currentTime-registTime.getTime();
            if (time/1000/60/60>24){
                throw new ActiveUserException(ResponseCode.ERROR_EXPIRE);
            }
            userDao.activeUser(activeCode);
        } catch (SQLException e) {
            throw new ActiveUserException(ResponseCode.ERROR_DB);
        }

    }

    public boolean register(User user){
        try {
            userDao.addUser(user);
            String emailMsg="感谢你注册网上书城，点击"
                    +"<a href='http://localhost:8080/activeUser?activeCode="
                    +user.getActiveCode() +"'>&nbsp;激活&nbsp;</a>后使用。"
                    +"<br/>为你的账号，请在24小时内完成激活";
            MailUtils.sendMail(user.getEmail(),emailMsg);
            return true;
        }catch (Exception e){
            return false;
        }
    }
    public User login(User user) throws LoginException{
//        如果登录成功，返回数据库用户记录对应java对象，否则抛出异常：用户未激活，用户不存在，用户密码错误
        UserDao userDao=new UserDao();
        User userDB=null;
        try{
            userDB=userDao.findUserByUsernameAndPassword(user.getUsername(),user.getPassword());
        }catch (SQLException e){
            e.printStackTrace();
            throw new LoginException(ResponseCode.ERROR_DB);
        }
        if (userDB!=null){
            if (userDB.getState()==1){
                return userDB;

            }else{
                throw new LoginException(ResponseCode.NOT_ACTIVE);
            }
        }else{
            throw new LoginException(ResponseCode.ERROR_NAME_PASSWORD);
        }
    }
}
